package com.lagou.service.impl;

import com.lagou.pojo.AuthToken;
import com.lagou.pojo.AuthUser;
import com.lagou.repository.AuthTokenRepository;
import com.lagou.repository.AuthUserRepository;
import com.lagou.service.UserService;
import com.lagou.service.VertifyCodeService;
import com.lagou.utils.MD5;
import com.lagou.vo.Result;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.Date;
import java.util.Optional;
import java.util.UUID;

/**
 * @ClassName: UserServiceImpl
 * @Auther: Jerry
 * @Date: 2020/10/22 19:27
 * @Desctiption: TODO
 * @Version: 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private AuthUserRepository repository;

    @Autowired
    private AuthTokenRepository tokenRepository;

    @Reference
    private VertifyCodeService vertifyCodeService;

    @Override
    public Boolean register(String email, String password, String code) {
        logger.info("request param[{}], [{}], [{}]", email, password, code);
        // 校验验证码是否正确，0正确1错误2超时
        Integer result = vertifyCodeService.validate(email, code);
        logger.info("response result[{}]", result);
        if (result == 0) {
            // 校验用户是否已存在
            AuthUser user = new AuthUser();
            user.setEmail(email);
            Example<AuthUser> example = Example.of(user);
            Optional<AuthUser> optional = repository.findOne(example);
            if (optional.isPresent()) {
                throw new RuntimeException("用户已经注册过了~");
            } else {
                AuthUser authUser = new AuthUser();
                // 保存用户信息
                authUser.setEmail(email);
                // 密码进行加密
                authUser.setPassword(MD5.md5(password, email));
                // 状态：0，正常；1，失效
                authUser.setStatus("0");
                authUser.setCreateTime(new Date());
                AuthUser saveUser = repository.save(authUser);

                if (saveUser == null) {
                    throw new RuntimeException("用户注册失败");
                }
                logger.info("user save success...");
                return true;
            }
        }
        logger.info("verify code is error or validate...");
        return false;
    }

    @Override
    public Boolean isRegistered(String email) {
        logger.info("request param[{}]", email);
        AuthUser user = new AuthUser();
        user.setEmail(email);
        user.setStatus("0");
        Example<AuthUser> example = Example.of(user);
        // 根据邮箱判断,存在说明已注册过
        Optional<AuthUser> optional = repository.findOne(example);
        logger.info("user isRegistered[{}]", optional.isPresent());

        return optional.isPresent() ? true : false;
    }

    @Override
    public Result<AuthToken> login(String email, String password) {
        logger.info("request param[{}], [{}]", email, password);
        AuthUser user = new AuthUser();
        user.setEmail(email);
        Example<AuthUser> example = Example.of(user);
        Optional<AuthUser> optional = repository.findOne(example);
        if (optional.isPresent()) {
            AuthUser authUser = optional.get();
            String md5Password = MD5.md5(password, email);
            // 密码不正确
            if (!authUser.getPassword().equals(md5Password)) {
                return Result.error("密码输入有误,请重试");
            }

            // 查询用户是否已生成token
            AuthToken authToken = new AuthToken();
            authToken.setEmail(email);
            Example<AuthToken> authTokenExample = Example.of(authToken);
            Optional<AuthToken> tokenOptional = tokenRepository.findOne(authTokenExample);
            if (tokenOptional.isPresent()) {
                authToken = tokenOptional.get();
            } else {
                // 登录成功，生成token
                String token = UUID.randomUUID().toString().replaceAll("-", "");
                authToken = new AuthToken();
                authToken.setEmail(email);
                authToken.setToken(token);
                tokenRepository.save(authToken);
            }
            return Result.success(authToken);
        } else {
            return Result.error("用户不存在~");
        }
    }

    @Override
    public Result<AuthToken> info(String token) {
        AuthToken authToken = new AuthToken();
        authToken.setToken(token);
        Example<AuthToken> example = Example.of(authToken);
        // 查询此token是否存在
        Optional<AuthToken> optional = tokenRepository.findOne(example);
        if (optional.isPresent()) {
            return Result.success(optional.get());
        }
        return new Result<>();
    }

}
